################################################################################
# This script will loop through Tmax ASCII files and extract ones of interest
# 

################################################################################
#load necessary libraries

#list the libraries needed
necessary=c("adehabitat","SDMTools")

#check if library is installed
installed = necessary %in% installed.packages()

#if library is not installed, install it
if (length(necessary[!installed]) >=1) install.packages(necessary[!installed], dep = T)

#load the libraries
for (lib in necessary) library(lib,character.only=T)

################################################################################

# Define the year

year=2007

  #doy = 0 #track the number of days in the year
  for (month in 1:12) {
  
    #extract solar data for the month in question
    #t.join = solar.join[which(solar.join$month==12),1]
    #solar.asc = read.asc(paste(solar.dir,solar.join[which(solar.join$month==12),1],sep=""))
    #solar.mat = matrix(coefs[4],nrow(solar.asc), ncol(solar.asc))
    #solar.coef.asc = solar.asc * solar.mat
    
    #dom = 0 #track the number of days in the month
    for (day in 1:31) {
      
      #calculate the date
      tdate = format(as.Date(paste(year,month,day,sep="-"),"%Y-%m-%d"),"%Y%m%d")
      
      #if the date exists as a file... start the summary
      tfile = paste(tmax.dir,"tmax.",tdate,tdate,".grid.gz",sep="")
      if (file.exists(tfile)){  cat(tfile,'\n')
           
        #unzip the file and import the asc file
        tmax.asc = read.asc.gz(tfile)
        
        #write out .asc files
        write.asc(tmax.asc,paste(out.dir,tdate,".asc",sep=""))
                
          #ensure the layer has data in it
          if (length(which(!is.na(tmax.asc)))>0) {

            
            
    
          }
        }
      }
    }
